# coding=utf-8
#! /usr/bin/python

"""
__author__='wudi'
@File:attach_email.py
@Time:2017/5/25 16:43
"""
#解决编码不一致问题
import sys

reload(sys)
sys.setdefaultencoding("utf-8")

import sys
import locale
import poplib
from email import parser
import email
import string
from email.parser import Parser
import datetime
import base64

from autorun import runTask  #引用自动运行函数


# 确定运行环境的encoding
__g_codeset = sys.getdefaultencoding()
if "ascii"==__g_codeset:
    __g_codeset = locale.getdefaultlocale()[1]


def object2double(obj):
    if(obj==None or obj==""):
        return 0
    else:
        return float(obj)



#处理编码1
def utf8_to_mbs(s):
    return s.decode("utf-8").encode("gb2312")

#处理编码2
def mbs_to_utf8(s):
    return s.decode("gbk").encode("utf-8")


host = 'pop.exmail.qq.com'
username = 'fjdkfiejfdsaj@qq.com'    #指定邮箱
password = 'dieksl847d=' #邮箱密码

pop_conn = poplib.POP3(host)
pop_conn.user(username)
pop_conn.pass_(password)

#定义发送者和主题
Fromuser = 'iekd@qq.com'
Subject = u'销售达成日报'
time = 30000  #3600秒,10小时内邮件取出
#延迟时间
sleeptime_day = 0
sleeptime_min = 0
sleeptime_hour = 0
sleeptime_second = 3600   #86400秒，间隔24小时

# 获得邮件

messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# print messages

#print "--------------------------------------------------"
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
# print messages

#Parse message intom an email object:
# 分析
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
#print len(messages)
# print messages[0]

def fun_downimg(filepath = None,argum = None):
    i = 0
    for index in range(0,len(messages)):   #遍历邮件
        message = messages[index];
        i = i + 1;
        fromuser = email.utils.parseaddr(message.get('from'))[1]
        #判断是某用户发来的邮件
        if fromuser == Fromuser:

            subject = message.get('subject')
            h = email.Header.Header(subject)
            dh = email.Header.decode_header(h)
            subject = unicode(dh[0][0], dh[0][1]).encode('utf8')
            #判断主题是“销售达成日报”的邮件
            if subject == Subject:

                datestring = message["Date"]
                index_start = datestring.index(',')
                index_end = datestring.index('+')
                datestring = datestring[index_start+2:index_end-1]
                # print datestring
                ddate = datetime.datetime.strptime(datestring,'%d %b %Y %H:%M:%S')
                # print ddate
                date_now = datetime.datetime.now()
                # print date_now
                # print (date_now-ddate).seconds
                #
                # print ddate.strftime('%Y-%m-%d')
                #判断日期在设定变量内的邮件
                if ddate.strftime('%Y-%m-%d')==date_now.strftime('%Y-%m-%d') and (date_now-ddate).seconds <= time:
                    print subject
                    print fromuser
                    print (date_now-ddate).seconds
                    mailName = "mail%d.%s" % (i, subject)
                    f = open('%s%d.log'%(filepath,i), 'w')
                    print >> f, "Date: ", message["Date"]
                    print >> f, "From: ", email.utils.parseaddr(message.get('from'))[1]
                    print >> f, "To: ", email.utils.parseaddr(message.get('to'))[1]
                    print >> f, "Subject: ", subject
                    print >> f, "Data: "
                    j = 0
                    for part in message.walk():
                        j = j + 1
                        fileName = part.get_filename()
                        contentType = part.get_content_type()
                        mycode=part.get_content_charset();
                        # 保存附件
                        if fileName:
                            data = part.get_payload(decode=True)
                            h = email.Header.Header(fileName)
                            dh = email.Header.decode_header(h)
                            fname = dh[0][0]
                            encodeStr = dh[0][1]
                            if encodeStr != None:
                                fname = fname.decode(encodeStr, mycode)
                            #end if
                            fEx = open("%s%s"%(filepath,fname), 'wb')
                            fEx.write(data)
                            fEx.close()
                        elif contentType == 'text/plain':# or contentType == 'text/html':
                            #保存正文
                            data = part.get_payload(decode=True)
                            content=str(data)
                            if mycode=='gb2312':
                                content= mbs_to_utf8(content)
                            print >> f, data
                    break
                        #end if
                    #end for
                    f.close()
    #end for

if __name__=="__main__":
    #拷贝或单独运行此程序时，若将filepath注释即自动将文件或日志写在当前程序目录下。
    #这里指定路径是为了方便linux在root用户下通过crontabe -e来写入计划任务，如果不指定路径，就会将文件保存在/root下。
    filepath = '/home/admin_wd/programe/python/autosend_towechat/'
    fun_downimg(filepath)
    # runTask(fun_downimg,argum=None,day=sleeptime_day, hour=sleeptime_hour, min=sleeptime_min, second=sleeptime_second)

    pop_conn.quit()
